<template>
    <el-container class="publish-task-container" direction="vertical">
        <el-container>
            <HeaderBtnGroup @handleClick="handleHeaderClick" :config="headerConfig">
            </HeaderBtnGroup>
        </el-container>
        <el-container>
            <div style="width:100%;">
                <el-table :data="targets" v-loading="loadingShow">
                    <el-table-column fixed label="序号" type="index" prop="id"></el-table-column>
                    <el-table-column label="关联帐号" width="150px" prop="accountId">
                        <template slot-scope="scope">
                            <span>{{ showAccountname(scope.row.accountId) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="任务名称" width="100px" prop="name"></el-table-column>
                    <el-table-column label="目标语言" width="100px" prop="lang">
                        <template slot-scope="scope">
                            <span>{{ showLangName(scope.row.lang) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="目标平台" prop="platformId">
                        <template slot-scope="scope">
                            <span>{{ showPlatform(scope.row.platformId) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="主页链接" width="200px" prop="homeUrl"></el-table-column>
                    <el-table-column label="小组链接" width="200px" prop="targetUrl"></el-table-column>
                    <el-table-column label="操作" width="210px" fixed="right">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" @click="handleEnable(scope.row)">{{
                scope.row.enable == 1 ?
                    "失效" : "生效" }}</el-button>
                            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
                                编辑</el-button>
                            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-container>
        <el-dialog title="添加任务" :visible.sync="dialogFormVisible" destroy-on-close @close="handleDialogClose"
            width="650px">
            <el-form :model="form" ref="addForm" label-position="right" :rules="rules">
                <el-container class="select-container">
                    <el-form-item label="发布平台" class="direction-hor" :label-width="formLableWidth">
                        <el-select v-model="form.platformId" @change="handlePlatformChanged" placeholder="请选择平台">
                            <el-option v-for="item in platforms" :key="'platform' + item.id" :value="item.id"
                                :label="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="发布规则" class="direction-hor" :label-width="formLableWidth">
                        <el-select v-model="form.ruleId" placeholder="请选择发布规则">
                            <el-option v-for="item in ruleOptions" :key="'rule' + item.id" :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-container>
                <el-container class="select-container">
                    <el-form-item label="关联帐号" class="direction-hor" :label-width="formLableWidth">
                        <el-select v-model="form.accountId" placeholder="请选择帐号">
                            <el-option v-for="item in platformAccounts" :key="'account' + item.id" :value="item.id"
                                :label="item.account"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="目标语言" class="direction-hor" :label-width="formLableWidth">
                        <el-select v-model="form.lang" placeholder="请选择语言">
                            <el-option v-for="item in langs" :key="'lang' + item.id" :value="item.id"
                                :label="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-container>
                <el-form-item label="数据字段" :label-width="formLableWidth">
                    <el-select v-model="form.dataFields" multiple placeholder="请选择字段">
                        <el-option v-for="item in fields" :key="item.targetField" :label="item.targetField"
                            :value="item.targetField">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称" :label-width="formLableWidth">
                    <el-input v-model="form.name" auto-complete="off" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="主页链接" :label-width="formLableWidth">
                    <el-input v-model="form.homeUrl" auto-complete="off" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="小组链接" :label-width="formLableWidth">
                    <el-input v-model="form.targetUrl" auto-complete="off" size="mini"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
                <el-button type="primary" @click="handleSaveData('addForm')" size="mini">确 定</el-button>
            </div>
        </el-dialog>
    </el-container>
</template>

<style lang="scss">
.publish-task-container {
    .el-dialog__body {
        padding-bottom: 0px !important;
        padding-top: 10px !important;
    }

    .select-container {
        margin-left: 0px;
        margin-bottom: 18px;

        .direction-hor {
            display: inline-block;
            margin-bottom: 0px !important;

            .el-form-item__label {
                width: auto;
            }

            .el-form-item__content {
                width: auto;
            }
        }
    }

    .el-select {
        width: 100%;
    }
}
</style>

<script>
import { RuleDao } from '@/dao/ruleDao'
import { DictDao } from "@/dao/dictDao"
import { TaskDao } from '@/dao/taskDao'
import { DeepCopy } from '@/utils/Utils'
import { AccountDao } from '@/dao/accountDao'
import { PromotionDao } from '@/dao/promotionDao'
import { HeaderBtnMixin } from "@/mixins/HeaderBtnMixin"
import HeaderBtnGroup from "@/components/Common/HeaderBtnGroup"
import { DictType, UsageScope, Lang } from '@/entities/Constant'
export default {
    name: "TaskGroup",
    mixins: [HeaderBtnMixin],
    components: { HeaderBtnGroup },
    props: {
        usage: {
            type: Number,
            default: 0,
        }
    },
    data() {
        return {
            rules: {},
            langs: [],
            fields: [],
            targets: [],
            accounts: [],
            platforms: [],
            ruleOptions: [],
            loadingShow: true,
            lastPlatformId: 0,
            platformAccounts: [],
            formLableWidth: "100px",
            form: TaskDao.initialForm(this.usage),
            headerConfig: {
                pageSize: TaskDao.pageSize,
                statusBtns: [],
            }
        }
    },
    mounted() {
        this.getTargets(this.page, async () => {
            this.langs = Lang.Options()
            this.fields = await PromotionDao.getFields()
            this.accounts = await AccountDao.fetchAll(this.usage)
            this.platforms = await DictDao.Platforms(DictType.Platform, this.usage)
        })
    },
    methods: {
        getTargets(page, fn) {
            this.loadingShow = true
            TaskDao.fetchCount(page, this.usage).then((res) => {
                if (fn) {
                    fn().then(() => {
                        this.loadingShow = false
                        this.headerConfig.total = res.count
                        if (res.count > 0) this.targets = res.datas
                    })
                } else {
                    this.loadingShow = false
                    this.headerConfig.total = res.count
                    if (res.count > 0) this.targets = res.datas
                }
            })
        },
        showPlatform(value) {
            let obj = this.platforms.find(obj => obj.id == value)
            return obj ? obj.name : ""
        },
        showLangName(value) {
            let obj = this.langs.find(obj => obj.id == value)
            return obj ? obj.name : ""

        },
        showAccountname(value) {
            let obj = this.accounts.find(obj => obj.id == value)
            return obj ? obj.account : ""
        },
        handleEdit(row) {
            if (this.usage == UsageScope.Publisher) {
                this.getRulesAndAccounts(this.usage, row.platformId).then(() => {
                    this.$nextTick(() => {
                        this.form = TaskDao.toObject(row)
                        this.dialogFormVisible = true
                    })
                })
            } else {
                this.form = TaskDao.toObject(row)
                this.dialogFormVisible = true
            }
        },
        handleDelete(id) {
            TaskDao.delete(id).then(res => this.getTargets(this.page))
        },
        handleDialogClose() {
            this.form = TaskDao.initialForm(this.usage)
        },
        handleEnable(row) {
            let obj = DeepCopy(row)
            if (obj.enable == 0) {
                obj.enable = 1
            } else {
                obj.enable = 0
            }
            TaskDao.save(obj).then(res => this.getTargets(this.page))
        },
        handleSaveData(formName) {
            const formData = TaskDao.toObject(this.form)
            formData.moduleId = this.getModuleId(formData)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    TaskDao.save(formData).then((res) => {
                        if (res > 0) {
                            this.getTargets(this.page)
                            this.dialogFormVisible = false
                            this.$message.success("保存成功")
                        } else {
                            this.$message.error("保存失败")
                        }
                    }).catch(err => {
                        this.$message.error("保存失败")
                    })
                }
            })
        },
        getModuleId(form) {
            let obj = this.ruleOptions.find(item => item.id == form.ruleId)
            return obj.moduleId
        },
        async getRulesAndAccounts(usageScope, platformId) {
            let whereDict = {
                usageScope: usageScope,
                platformId: platformId
            }
            this.ruleOptions = await RuleDao.fetchAll(whereDict)
            this.platformAccounts = await AccountDao.fetchAll(usageScope, platformId)
        },
        handlePlatformChanged(platformId) {
            if (this.lastPlatformId == platformId) {
                return
            }
            this.form.ruleId = ""
            this.form.accountId = ""
            this.lastPlatformId = platformId
            this.getRulesAndAccounts(this.usage, platformId)
        }
    },
}
</script>
